package com.wodwl.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.converter.api.ConverterAPI;
import com.wodwl.configuration.ResourceConfiguration;
import com.wodwl.configuration.Helper;
import com.wodwl.dao.ResourceDao;
import com.wodwl.dao.ResourceDao.Mode;
import com.wodwl.dao.UserDao;
import com.wodwl.entity.Resource;
import com.wodwl.entity.User;


@Controller
public class ResourceController {
	private String resource_add_view="/resource/resource_add";
	private String resource_add_success_view="/resource/resource_list";
	private String resource_list_view="/resource/resource_list";
	private String resource_show_view="/resource/resource_show";
	private String resource_editor_view="/resource/resource_editor";
	private String resource_add_failure_view="/resource/resource_add_failure";
	
	//计算文件大小
	//bt字节参考量
	public static final long SIZE_BT=1024L;
	//KB字节参考量
	public static final long SIZE_KB=SIZE_BT*1024L;
	//MB字节参考量
	public static final long SIZE_MB=SIZE_KB*1024L;
	//GB字节参考量
	public static final long SIZE_GB=SIZE_MB*1024L;
	//TB字节参考量
	public static final long SIZE_TB=SIZE_GB*1024L;



	
	@RequestMapping("/resource/resource_editor1.do")
	 public ModelAndView editorInfo1(HttpServletRequest request,HttpServletResponse response) {

		Map map=new Hashtable();
		ResourceDao dao2=new ResourceDao();
		Resource resource=dao2.getResourceByRid(Integer.parseInt(request.getParameter("rid")));
		map.put("resource", resource);
		return new ModelAndView(getResource_editor_view(),map);
	}
	
	
	@RequestMapping("/resource/resource_editor2.do")
	 public ModelAndView editorInfo2(HttpServletRequest request,HttpServletResponse response) {
		
		Resource resource=new Resource();
		resource.setRid(Integer.parseInt(request.getParameter("rid")));
		resource.setName(request.getParameter("name"));
		resource.setType(Integer.parseInt(request.getParameter("type")));
		resource.setCategory(Integer.parseInt(request.getParameter("category")));
		resource.setTag(request.getParameter("tag"));
		resource.setDescription(request.getParameter("description"));
		
		ResourceDao dao=new ResourceDao();
		dao.update(resource, Mode.UPDATE);
		
		return showResource(request, response);
		
	}
	

	@RequestMapping("/resource/resource_show.do")
	 public ModelAndView showResource(HttpServletRequest request,HttpServletResponse response) {
		Map map=new Hashtable();
		ResourceDao dao=new ResourceDao();
		Resource resource=dao.getResourceByRid(Integer.parseInt(request.getParameter("rid")));
		map.put("resource", resource);
		return new ModelAndView(getResource_show_view(),map);
	}
	
	@RequestMapping("/resource/resource_list.do")
    public void listResource(HttpServletRequest request,HttpServletResponse response) throws IOException, JSONException {
		
		JSONObject jsonObject=new JSONObject();
		String path=request.getParameter("path");
		int pid=Integer.parseInt(path.substring(path.lastIndexOf("a")+1));
		ResourceDao dao=new ResourceDao();
		List<Resource> resources=dao.getResourcesByPid(pid);
		JSONArray jsonArray=new JSONArray();
		for(int i=0;i<resources.size();i++){
			jsonArray.put(resources.get(i).toJsonObject());
		}
		jsonObject.put("resources",jsonArray);
		jsonObject.put("path",path);
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(jsonObject);
    }
	@RequestMapping("/resource/get_droped_resources.do")
    public void getDropedResources(HttpServletRequest request,HttpServletResponse response) throws IOException, JSONException {
		
		JSONObject jsonObject=new JSONObject();
		ResourceDao dao=new ResourceDao();
		HttpSession session=request.getSession();
		User user=(User)session.getAttribute("g305_user");
		List<Resource> resources=dao.getDropedResources(user.getUsername());
		JSONArray jsonArray=new JSONArray();
		for(int i=0;i<resources.size();i++){
			jsonArray.put(resources.get(i).toJsonObject());
		}
		jsonObject.put("resources",jsonArray);
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(jsonObject);
    }
	
	@RequestMapping(value="/resource/resource_add.do",method = RequestMethod.POST)
    public ModelAndView addResource(HttpServletRequest request,HttpServletResponse response
    		,@RequestParam("file") MultipartFile file) throws IOException {
		
		Resource resource=new Resource();
		boolean flag=Helper.uploadFile(file, ResourceConfiguration.rootDir, ResourceConfiguration.resource_source);
		if(!flag){
			 return new ModelAndView(getResource_add_failure_view(),null);
		}
		resource.setOrgi_file_name(Helper.UploadFileNode.originalFileName);
		resource.setSize(Helper.UploadFileNode.size);
		resource.setStore_relative_path(Helper.UploadFileNode.storeRelativePath);
		String path=request.getParameter("path");
		resource.setPath(path);
		int pid=Integer.parseInt(path.substring(path.lastIndexOf("a")+1));
		resource.setPid(pid);
		resource.setName(request.getParameter("name"));
		
		//文件转换
		String str=resource.getStore_relative_path();
		flag=ConverterAPI.convert(str.substring(str.lastIndexOf("/")+1));
		if(!flag){
			return new ModelAndView(getResource_add_failure_view(),null);
		}
		
		
		//判断文件类型
		String ext=Helper.UploadFileNode.ext;
		if(ext.equalsIgnoreCase("txt")){
			resource.setType(Resource.TypeIndex.TXT);
		}else if(ext.equalsIgnoreCase("doc")||ext.equalsIgnoreCase("docx")){
			resource.setType(Resource.TypeIndex.WORD);
		}else if(ext.equalsIgnoreCase("xls")||ext.equalsIgnoreCase("xlsx")){
			resource.setType(Resource.TypeIndex.EXCEL);
		}else if(ext.equalsIgnoreCase("ppt")||ext.equalsIgnoreCase("pptx")){
			resource.setType(Resource.TypeIndex.PPT);
		}else if(ext.equalsIgnoreCase("jpg")||ext.equalsIgnoreCase("png")||ext.equalsIgnoreCase("ico")||ext.equalsIgnoreCase("bmp")){
			resource.setType(Resource.TypeIndex.PICTURE);
		}else if(ext.equalsIgnoreCase("mp3")||ext.equalsIgnoreCase("wma")||ext.equalsIgnoreCase("flac")||ext.equalsIgnoreCase("aac")||ext.equalsIgnoreCase("amr")){
			resource.setType(Resource.TypeIndex.MUSIC);
		}else if(ext.equalsIgnoreCase("mp4")||ext.equalsIgnoreCase("avi")||ext.equalsIgnoreCase("rmvb")||ext.equalsIgnoreCase("gif")||ext.equalsIgnoreCase("wmv")){
			resource.setType(Resource.TypeIndex.MOVIE);
		}else if(ext.equalsIgnoreCase("war")){
			resource.setType(Resource.TypeIndex.WAR);
		}else{
			resource.setType(Resource.TypeIndex.OTHER);
		}
		
		
		resource.setCategory(Integer.parseInt(request.getParameter("category")));
		resource.setTag(request.getParameter("tag"));
		resource.setDescription(request.getParameter("description"));
		HttpSession session=request.getSession();
		User user=(User)session.getAttribute("g305_user");
		resource.setOwner(user.getUsername());
		long time=System.currentTimeMillis();
		resource.setCreate_time(time);
		resource.setLast_modify_time(time);
		resource.setDownload_count(0);
		resource.setStatus(Resource.Status.Nomal);
		ResourceDao dao=new ResourceDao();
		dao.update(resource, Mode.INSERT);
		
		dao=new ResourceDao();
		List<Resource> resources=dao.getResourcesByPid(pid);
		Map map=new Hashtable();
		map.put("resources", resources);
		request.setAttribute("path", path);

		return new ModelAndView(getResource_list_view(),map);
		
    }
	@RequestMapping(value="/resource/add_folder.do")
    public void addFolder(HttpServletRequest request,HttpServletResponse response) throws IOException, JSONException {
		Resource resource=new Resource();
		String path=request.getParameter("path");
		int pid=Integer.parseInt(path.substring(path.lastIndexOf("a")+1));
		resource.setPid(pid);
		resource.setPath(path);
		resource.setStatus(Resource.Status.Nomal);
		String name=URLDecoder.decode(request.getParameter("name"),"utf-8");
		resource.setName(name);
		resource.setType(Resource.TypeIndex.FOLDER);
		HttpSession session=request.getSession();
		User user=(User)session.getAttribute("g305_user");
		resource.setOwner(user.getUsername());
		long time=System.currentTimeMillis();
		resource.setCreate_time(time);
		resource.setLast_modify_time(time);
		
		ResourceDao dao=new ResourceDao();
		dao.update(resource, Mode.INSERT);
		/*
		dao=new ResourceDao();
		List<Resource> resources=dao.getResourcesByPid(pid);
		Map map=new Hashtable();
		map.put("resources", resources);
		map.put("path", path);
		*/
		//return new ModelAndView(getResource_list_view(),map);
		listResource(request, response);
		
    }
	@RequestMapping(value="/resource/rename.do")
    public void reName(HttpServletRequest request,HttpServletResponse response) throws IOException {
		int rid=Integer.parseInt(request.getParameter("rid"));
		String name=URLDecoder.decode(request.getParameter("name"),"utf-8");
		ResourceDao dao=new ResourceDao();
		dao.modifyNameByRid(rid, name,System.currentTimeMillis());
		
	}
	@RequestMapping(value="/resource/delete.do")
    public void delete(HttpServletRequest request,HttpServletResponse response) throws IOException {
		int rid=Integer.parseInt(request.getParameter("rid"));
		String path=request.getParameter("path");
		ResourceDao dao=new ResourceDao();
		dao.deleteByRid(rid);
		Map map=new Hashtable();
		map.put("path", path+"a"+rid+"%");
		map.put("last_modify_time", System.currentTimeMillis());
		dao.deleteResourcesByPath(map);
	}
	//回收站恢复
	@RequestMapping(value="/resource/restore.do")
    public void restore(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String path=request.getParameter("path");
		int rid=Integer.parseInt(path.substring(path.lastIndexOf("a")+1));
		ResourceDao dao=new ResourceDao();
		dao.restoreByRid(rid);
		dao.restoreResourcesByPath(path);
		
	}
	//清空回收站
	@RequestMapping(value="/resource/clear_dash.do")
    public void clearDash(HttpServletRequest request,HttpServletResponse response) throws IOException {
		HttpSession session=request.getSession();
		User user=(User)session.getAttribute("g305_user");
		ResourceDao dao=new ResourceDao();
		dao.clearDash(user.getUsername());	
	}
	
	public String getFileSize(MultipartFile f)throws RuntimeException
	{
	   long size=f.getSize();
	   
	    if(size>=0&&size<SIZE_BT)
	    {
	     return size+"B";
	    }else if(size>=SIZE_BT&&size<SIZE_KB)
	    {
	     return size/SIZE_BT+"KB";
	    }else if(size>=SIZE_KB&&size<SIZE_MB)
	    {
	     return size/SIZE_KB+"MB";
	    }
	    return new Long(size).toString();
	}


	
	@RequestMapping("/resource/resource_add_view.do")
    public String addResourceView(HttpServletRequest request,HttpServletResponse response) {
		request.setAttribute("path", request.getParameter("path"));
        return getResource_add_view();
    }

	public String getResource_add_view() {
		return resource_add_view;
	}

	public void setResource_add_view(String resource_add_view) {
		this.resource_add_view = resource_add_view;
	}

	public String getResource_add_success_view() {
		return resource_add_success_view;
	}

	public void setResource_add_success_view(String resource_add_success_view) {
		this.resource_add_success_view = resource_add_success_view;
	}

	public String getResource_list_view() {
		return resource_list_view;
	}

	public void setResource_list_view(String resource_list_view) {
		this.resource_list_view = resource_list_view;
	}

	public String getResource_show_view() {
		return resource_show_view;
	}

	public void setResource_show_view(String resource_show_view) {
		this.resource_show_view = resource_show_view;
	}

	public String getResource_editor_view() {
		return resource_editor_view;
	}

	public void setResource_editor_view(String resource_editor_view) {
		this.resource_editor_view = resource_editor_view;
	}


	public String getResource_add_failure_view() {
		return resource_add_failure_view;
	}


	public void setResource_add_failure_view(String resource_add_failure_view) {
		this.resource_add_failure_view = resource_add_failure_view;
	}
	
	
	
}
